package com.xp.pgoj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xp.pgoj.common.ErrorCode;
import com.xp.pgoj.constant.CommonConstant;
import com.xp.pgoj.exception.BusinessException;
import com.xp.pgoj.mapper.CommentMapper;
import com.xp.pgoj.mapper.UserMapper;
import com.xp.pgoj.model.dto.comment.CommentQueryRequest;
import com.xp.pgoj.model.entity.Comment;
import com.xp.pgoj.model.entity.User;
import com.xp.pgoj.model.vo.CommentVO;
import com.xp.pgoj.service.CommentService;
import com.xp.pgoj.utils.SqlUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.xp.pgoj.constant.UserConstant.USER_LOGIN_STATE;

/**
* @author xiaogeer
* @description 针对表【comment(评论表
)】的数据库操作Service实现
* @createDate 2024-09-25 15:16:02
*/
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment>
    implements CommentService {

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private UserMapper userMapper;

    @Override
    public QueryWrapper<Comment> getQueryWrapper(CommentQueryRequest commentQueryRequest) {
        if (commentQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = commentQueryRequest.getId();
        String content = commentQueryRequest.getContent();
        Long questionId = commentQueryRequest.getQuestionId();
        Long userId = commentQueryRequest.getUserId();
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(questionId != null, "questionId", questionId);
        String sortField = commentQueryRequest.getSortField();
        String sortOrder = commentQueryRequest.getSortOrder();
        // 固定创建时间为升序排序
        queryWrapper.orderByDesc("createTime");

        // 动态添加其他排序条件
        if (SqlUtils.validSortField(sortField)) {
            if (CommonConstant.SORT_ORDER_ASC.equals(sortOrder)) {
                queryWrapper.orderByAsc(sortField);
            } else {
                queryWrapper.orderByDesc(sortField);
            }
        }
        return queryWrapper;
    }

    @Override
    public Page<CommentVO> getCommentVOPage(Page<Comment> commentPage, HttpServletRequest request) {
        List<Comment> commentList = commentPage.getRecords();
        Page<CommentVO> commentVOPage = new Page<>(commentPage.getCurrent(), commentPage.getSize(), commentPage.getTotal());
        if (CollectionUtils.isEmpty(commentList)) {
            return commentVOPage;
        }
        List<CommentVO> commentVOList = commentList.stream()
                .map(comment -> getCommentVO(comment))
                .collect(Collectors.toList());
        commentVOPage.setRecords(commentVOList);
        return commentVOPage;
    }

    private CommentVO getCommentVO(Comment comment) {
        CommentVO commentVO = new CommentVO();
        User user = userMapper.selectById(comment.getUserId());
        BeanUtils.copyProperties(comment, commentVO);
        commentVO.setUserName(user.getUserName());
        commentVO.setUserAvatar(user.getUserAvatar());
        return commentVO;
    }

    @Override
    public List<CommentVO> getCommentVOList(List<Comment> commentList, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        List<CommentVO> commentVOList = new ArrayList<>();
        Long userId = user.getId();
        for (int i = 0; i < commentList.size(); i++) {
            CommentVO commentVO = new CommentVO();
            Comment comment = commentList.get(i);
            BeanUtils.copyProperties(comment, commentVO);
            Long commentUserId = comment.getUserId();
            // 判断当前用户是否为评论用户
            if (commentUserId == userId) {
                commentVO.setIsPublisher(1);
            }
            commentVOList.add(commentVO);
        }
        return commentVOList;
    }

    @Override
    public List<Comment> getCommentListByQuestionId(Long questionId) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("questionId", questionId);
        List<Comment> comments = commentMapper.selectList(queryWrapper);
        return comments;
    }

    @Override
    public boolean addComment(Comment comment, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        Long userId = user.getId();
        Long commentUserId = comment.getUserId();
        if (commentUserId.equals(userId)) {
            comment.setIsPublisher(1);
        }
        return this.save(comment);
    }
}




